import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { login } from './indexApi';
import { setToken, setUserInfo } from '../../utils/localStorge';
import { LoginProps } from './types';

const initialState = {
  status: 'idle',
};
export const loginAsync = createAsyncThunk(
  'auth/login',
  async (queryParams: LoginProps) => {
    const res: any = await login(queryParams);
    return res.data;
  }
);

export const loginSlice = createSlice({
  name: 'loginInfo',
  initialState,
  reducers: {
    increment: (state) => {
      // console.log(122);
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      // state.value += action.payload;
    },
  },
  // The `extraReducers` field lets the slice handle actions defined elsewhere,
  // including actions generated by createAsyncThunk or in other slices.
  extraReducers: (builder) => {
    builder.addCase(loginAsync.pending, (state, action) => {
      state.status = 'pending';
    }),
      builder.addCase(loginAsync.fulfilled, (state, action) => {
        setToken(action.payload.token);
        setUserInfo(JSON.stringify(action.payload));
      }),
      builder.addCase(loginAsync.rejected, (state, action) => {
        state.status = 'rejected';
      });
  },
});

export default loginSlice.reducer;
